//
//  OYCMainController.swift
//  WeiBo-Swift
//
//  Created by daniel on 2017/7/24.
//  Copyright © 2017年 daniel. All rights reserved.
//

import UIKit

class OYCMainController: UITabBarController {

    // MARK: 懒加载控件
    /// 撰写按钮
    fileprivate lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
    @objc fileprivate func composedButtonClick() {
        print(#function)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        setupComposedButton()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubview(toFront: composedButton)
    }
    
    

}

// MARK: - 设置界面
extension OYCMainController {
    
    fileprivate func setupComposedButton() {
        
        // 2. 设置按钮位置
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composedButton.addTarget(self, action: #selector(OYCMainController.composedButtonClick), for: .touchUpInside)
        
        tabBar.addSubview(composedButton)
    }
    
    // MARK: - 添加子控制器s
    fileprivate func addChildViewControllers() {
        
        addChildViewController(OYCHomeController(), itemIcon: "tabbar_home", itemTitle: "首页")
        addChildViewController(OYCMessageController(), itemIcon: "tabbar_message_center", itemTitle: "消息")
        addChildViewController(UIViewController())
        addChildViewController(OYCDiscoverController(), itemIcon: "tabbar_discover", itemTitle: "发现")
        addChildViewController(OYCProfileController(), itemIcon: "tabbar_profile", itemTitle: "我")
        
    }
    
    fileprivate func addChildViewController(_ childController: UIViewController, itemIcon: String, itemTitle: String) {
        
        childController.tabBarItem.image = UIImage(named: itemIcon)
        childController.tabBarItem.selectedImage = UIImage(named: itemIcon + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        childController.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .selected)
        childController.title = itemTitle
        
        let nav = UINavigationController.init(rootViewController: childController)
        
        addChildViewController(nav)
        
    }
    
}

